var server = require("./server");
var url = require("url");
var mustache = require('mustache');
var fs = require('fs');

template = fs.readFileSync('./table_template.html', 'utf8')


// Connect to DB
var databaseUrl = "62.109.16.96/test"; 
var collections = ["tables"]
var db = require("mongojs").connect(databaseUrl, collections);

// Start server
var handle = {	"/": 			hello,
				"/table": 		table,
				"/hello": 		hello,
				"/favicon.ico": ignore,
				}


server.start(route, handle);




function route(handle, location, response) 
{
  	console.log("Looking for " + location);

  	var pathname = url.parse(location).pathname;
  	if (typeof handle[pathname] === 'function') 
  	{
    	handle[pathname](location, response);
  	} 
  	else
  	{
	    console.log("No request handler found for " + pathname);
	    response.writeHead(404, {"Content-Type": "text/plain"});
	    response.write("404 Not found");
	    response.end();
  	}
}


function table(location, response)
{
	find_table(url.parse(location, true).query.date, response);
}


function find_table(ldate, response)
{
	console.log('asking for ', ldate)
	
	db.tables.find({date:ldate}).forEach(function(err, data) 
	{
		if (data)
	 	{
			response.write(mustache.render(template, data));
    		response.end();
	 	}
	 	else
	 	{
    		response.end('No table for date ' + ldate);
	 	}
	}
	);

}


function hello(location, response) 
{
  console.log("Request handler 'hello' was called.");
  response.writeHead(200, {"Content-Type": "text/plain"});
  response.write("Hello, World!");
  response.end();
}

function ignore(location, response) 
{
  response.end();
}
